package com.myexample.computerinternetdemo.presenter;

import com.myexample.computerinternetdemo.model.IConnect;
import com.myexample.computerinternetdemo.model.impl.ClientConnect;
import com.myexample.computerinternetdemo.view.IMainActView;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MainActPresenter {

    private IConnect iConnect = null;
    private IMainActView iMainActView = null;
    private final ThreadPoolExecutor executor;
    private volatile String textFromServer;

    public MainActPresenter() {
        executor = new ThreadPoolExecutor(2, 5, 30, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
    }
    public void connected(String ip){
        iConnect.connected(ip);
    }
    public void setMainActView(IMainActView iMainActView) {
        this.iMainActView = iMainActView;
    }

    public void newInstance() {
        this.iConnect = new ClientConnect();

    }
    public boolean isConnected(){
        return iConnect!=null&&iConnect.isConnected();
    }
    /**
     * 发送文本到服务器
     */
    public void sendTextToServer() {
        if (iConnect != null) {
            executor.execute(() -> {
                String text = iMainActView.getEditTextText();
                iConnect.sendTextToServer(text);
            });

            executor.execute(() -> {
                textFromServer = iConnect.getTextFromServer();
            });

        }
    }
    public void clearEditText(){
        iMainActView.clearEditText();
    }

    /**
     * 设置从服务器中获取的文本
     */
    public String getTextFromServer() {
        if (iConnect != null) {
            /*executor.execute(() -> {
                textFromServer = iConnect.getTextFromServer();
            });*/
            return textFromServer;
        }
        return null;
    }
    public void setText(String text){
        iMainActView.setText(text);
    }

    public void setWillSentText() {
        iMainActView.setSendText();
    }
    public void showToast(String text){
        iMainActView.showToast(text);
    }

    public void close() {
        //executor.shutdown();
        iConnect.close();
    }

    public void clearShowText() {
        iMainActView.clearShowText();
    }
}
